import React, { Component } from 'react'
import {Table,Button,Modal, Input,Form} from 'antd'
import { PlusOutlined, DeleteOutlined } from '@ant-design/icons';
import axios from 'axios';
import './Category.css'

export default class Category extends Component {
  state = {
    datalist:[],
    visible:false, //添加模态框是否显示
    visibleChild:false, //添加模态框是否显示
    childId:'',
    fatherlist:[],
    columns:[
      {
        title: '分类名',
        dataIndex: 'title',
        key: 'title',
      },
      {
        title: '操作',
        dataIndex: '',
        key: 'x',
        render: (item) => <div>
          {/* 添加分类 */}
          {item.children?
          <Button type="primary" shape="circle" icon={<PlusOutlined />} onClick={()=>this.handleAddChild(item)}/>
          :
          null
          }
          &nbsp;
          {/* 删除文章 */}
          {item.children?
          <Button type="danger" shape="circle" icon={<DeleteOutlined/>} onClick={()=>this.handleDelClick(item.id)}/>
          :
          null
          }
          </div>
      }
    ],
    // rowSelection :{
    //   onChange: (selectedRowKeys, selectedRows) => {
    //     console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
    //   },
    //   onSelect: (record, selected, selectedRows) => {
    //     console.log(record, selected, selectedRows);
    //   },
    //   onSelectAll: (selected, selectedRows, changeRows) => {
    //     console.log(selected, selectedRows, changeRows);
    //   },
    // }
  }
  render() {
    return (
      <div>
        <Button onClick={this.handleAdd} type="primary">添加分类</Button>
        <Table columns={this.state.columns} 
        // rowSelection={this.state.rowSelection} 
        dataSource={this.state.datalist} className="table"
        pagination={{pageSize:5}}  // 最多5行
        rowKey= {item=>{
          // console.log(item)
          return item.id
      }} //设置key值
        />
         {/* 添加用户 */}
         <Modal
          title="添加用户"
          visible={this.state.visible}
          onOk={this.handleOk}
          onCancel={() => {
            this.setState({
                visible: false
            })
        }}
        >
          <Form
            name="basic"
            // 垂直显示
            layout="vertical"
            ref="addform"
          >
            <Form.Item
              label="分类名"
              name="title"
              rules={[{ required: true, message: 'Please input title!' }]}
            >
              <Input />
            </Form.Item>
          </Form>
        </Modal>
        {/* 添加用户 */}
        <Modal
          title="添加用户"
          visible={this.state.visibleChild}
          onOk={this.handleChildOk}
          onCancel={() => {
            this.setState({
                visibleChild: false
            })
        }}
        >
          <Form
            name="basic1"
            // 垂直显示
            layout="vertical"
            ref="addformChild"
          >
            <Form.Item
              label="分类名"
              name="title"
              rules={[{ required: true, message: 'Please input title!' }]}
            >
              <Input />
            </Form.Item>
          </Form>
        </Modal>
      </div>
    )
  }

  // 获取初始文章
  componentDidMount() {
    axios.get("http://localhost:8000/categories").then(res =>{
      // 过滤后赋值
      this.setState({
        datalist:res.data
      })
    })
  }
   // 点击添加用户，模态框出现
   handleAdd = () =>{
    this.setState({
      visible: true
    })
  }

  handleAddChild = (item) =>{
    this.setState({
      visibleChild: true,
      childId: item.id,
      fatherlist:item
    })
  }
  // 点击确定，模态框隐藏，添加到数据库
  handleOk = () => {
    // 通过ref = addform 获取from表单
    this.refs.addform.validateFields().then(value =>{
      console.log(value);
      this.refs.addform.resetFields(); //重置表单
      axios.post("http://localhost:8000/categories",{title:value.title,default:true,value:value.title,children:[]}).then(res =>{
      // 重新设置datalist, 隐藏对话框
      this.setState({
        datalist:[...this.state.datalist,res.data],
        visible: false
      })
    })
    }).catch(info => {
      console.log('Validate Failed:', info);
    });
  }

  handleChildOk= () => {
    // 通过ref = addformChild 获取from表单
    this.refs.addformChild.validateFields().then(value =>{
      console.log(value);
      this.refs.addformChild.resetFields(); //重置表单

      // 添加新children，原来的children需要展开，否则会被覆盖
      axios.put(`http://localhost:8000/categories/${this.state.childId}`,{...this.state.fatherlist,children:[...this.state.fatherlist.children,{title:value.title,value:value.title,default:true}]}).then(res =>{
      // 重新设置datalist, 隐藏对话框
      this.setState({
        datalist:[...this.state.datalist.filter(item =>item.id !== this.state.childId),res.data],
        visibleChild: false
      })
    })
    }).catch(info => {
      console.log('Validate Failed:', info);
    });
  }
  // 删除
  handleDelClick = (id) =>{
    axios.delete(`http://localhost:8000/categories/${id}`).then(res =>{
      // 同步修改datalilst状态，
      console.log(res.data);
      
      this.setState({
      datalist:this.state.datalist.filter(item =>item.id !== id)
      })
    })
  }
}
